#include "key.h"
#include "config.h"

volatile uint8_t idata KeyCurrent, KeyOld, KeyNoChangedTime;
volatile uint8_t idata KeyPress;
volatile uint8_t idata KeyDown,KeyUp, KeyLast;
volatile uint8_t KeyCanChange;

void InitTimer0(void)
{
	TMOD &= 0xF0;
	TMOD |= 0x01;
	ET0 = 1;
	TR0 = 1;
}

/**********************************************
函数功能：键盘初始化
入口参数：无
返回：无
备注：无
***********************************************/
void InitKeyBoard(void)
{
	KeyIO = 0xFF;
	KeyPress = 0;
	KeyNoChangedTime = 0;
	KeyOld = 0;
	KeyCurrent = 0;
	KeyLast = 0;
	KeyDown = 0;
	KeyUp = 0;
	InitTimer0();
	KeyCanChange = 1;
}

/**************************************************
function: Timer0 interrupt handle
input: none
return: none
note: 22.1184MHz,about 5ms interrupt once.
**************************************************/
void Timer0Isr(void) interrupt 1
{
	TH0 = (65536-Fclk/1000/12*5 + 15)/256;
	TL0 = (65536-Fclk/1000/12*5+15)%256;
	if(!KeyCanChange) return;
	
	KeyCurrent = GetKeyValue();
	if(KeyCurrent!=KeyOld)
	{
		KeyNoChangedTime = 0;
		KeyOld = KeyCurrent;
		return;
	}
	else
	{
		KeyNoChangedTime++;
		if(KeyNoChangedTime>=1)
		{
			KeyNoChangedTime = 1;
			KeyPress = KeyOld;
			KeyDown |= (~KeyLast)&(KeyPress);
			KeyUp |= KeyLast&(~KeyPress);
			KeyLast = KeyPress;
		}
	}
}


